<template>
  <view class="app-bridge-test">
    <view class="header">
      <text class="title">APP Bridge 测试页面</text>
      <view class="status-box">
        <text class="status-label">Bridge 状态:</text>
        <text :class="['status-value', isInApp ? 'success' : 'warning']">
          {{ isInApp ? '✅ 已连接' : '⚠️ 未连接' }}
        </text>
      </view>
    </view>

    <view class="content">
      <!-- 登录测试 -->
      <view class="section">
        <text class="section-title">🔐 登录功能</text>
        <button class="btn btn-primary" @click="handleLogin">调用 APP 登录</button>
      </view>

      <!-- 用户信息 -->
      <!-- <view class="section">
        <text class="section-title">👤 用户信息</text>
        <button class="btn btn-info" @click="handleGetUserInfo">获取用户信息</button>
      </view> -->

      <!-- 分享功能 -->
      <!-- <view class="section">
        <text class="section-title">📤 分享功能</text>
        <button class="btn btn-success" @click="handleShare">调用分享</button>
      </view> -->

      <!-- 支付功能 -->
      <!-- <view class="section">
        <text class="section-title">💰 支付功能</text>
        <button class="btn btn-warning" @click="handlePay">调用支付</button>
      </view> -->

      <!-- 图片选择 -->
      <!-- <view class="section">
        <text class="section-title">🖼️ 图片选择</text>
        <button class="btn btn-secondary" @click="handleChooseImage">选择图片</button>
      </view> -->

      <!-- 定位功能 -->
      <!-- <view class="section">
        <text class="section-title">📍 定位功能</text>
        <button class="btn btn-info" @click="handleGetLocation">获取定位</button>
      </view> -->

      <!-- 其他功能 -->
      <!-- <view class="section">
        <text class="section-title">🛠️ 其他功能</text>
        <button class="btn btn-light" @click="handleSetTitle">设置标题</button>
        <button class="btn btn-danger" @click="handleClose">关闭 WebView</button>
      </view> -->

      <!-- 响应结果 -->
      <view class="result-box" v-if="resultText">
        <text class="result-title">📋 响应结果:</text>
        <text class="result-text">{{ resultText }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import {
  callAppLogin,
  registerLoginCallback,
  getAppUserInfo,
  callAppShare,
  callAppPay,
  closeAppWebView,
  setAppTitle,
  callAppChooseImage,
  getAppLocation,
  checkIsInApp
} from '@/utils/appBridge.js';

export default {
  name: 'AppBridgeTest',
  
  data() {
    return {
      isInApp: false,
      resultText: ''
    };
  },
  
  onLoad() {
    // 检测是否在 APP 环境中
    this.isInApp = checkIsInApp();
    console.log('[AppBridgeTest] 是否在 APP 中:', this.isInApp);
    
    // 注册登录回调
    registerLoginCallback((data) => {
      console.log('[AppBridgeTest] 收到登录回调:', data);
      this.showResult('收到 APP 登录回调', data);
      uni.showToast({
        title: '登录回调成功',
        icon: 'success'
      });
    });
  },
  
  methods: {
    // 显示结果
    showResult(title, data) {
      this.resultText = `${title}\n${JSON.stringify(data, null, 2)}`;
    },
    
    // 显示错误
    showError(error) {
      this.resultText = `❌ 错误: ${error.message || error}`;
      uni.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      });
    },
    
    // 检查 APP 环境
    checkAppEnv() {
      if (!this.isInApp) {
        uni.showToast({
          title: '请在 APP 中打开',
          icon: 'none'
        });
        return false;
      }
      return true;
    },
    
    // 调用登录
    async handleLogin() {
      if (!this.checkAppEnv()) return;
      
      try {
        console.log('[Test] 开始调用登录');
        console.log('[Test] Bridge 状态:', window.WebViewJavascriptBridge);
        console.log('[Test] UserAgent:', navigator.userAgent);
        
        uni.showLoading({ title: '登录中...' });
        
        const startTime = Date.now();
        const result = await callAppLogin({
          from: 'test-page'
        });
        const endTime = Date.now();
        
        console.log('[Test] 登录耗时:', (endTime - startTime) + 'ms');
        
        uni.hideLoading();
        this.showResult('登录成功', result);
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        });
      } catch (error) {
        uni.hideLoading();
        console.error('[Test] 登录错误:', error);
        console.error('[Test] 错误堆栈:', error.stack);
        this.showError(error);
      }
    },
    
    // 获取用户信息
    async handleGetUserInfo() {
      if (!this.checkAppEnv()) return;
      
      try {
        uni.showLoading({ title: '获取中...' });
        const result = await getAppUserInfo();
        uni.hideLoading();
        this.showResult('用户信息', result);
      } catch (error) {
        uni.hideLoading();
        this.showError(error);
      }
    },
    
    // 调用分享
    async handleShare() {
      if (!this.checkAppEnv()) return;
      
      try {
        const result = await callAppShare({
          title: '测试分享标题',
          content: '这是一个测试分享内容',
          url: 'https://example.com',
          imageUrl: 'https://example.com/image.jpg'
        });
        this.showResult('分享成功', result);
        uni.showToast({
          title: '分享成功',
          icon: 'success'
        });
      } catch (error) {
        this.showError(error);
      }
    },
    
    // 调用支付
    async handlePay() {
      if (!this.checkAppEnv()) return;
      
      try {
        uni.showLoading({ title: '支付中...' });
        const result = await callAppPay({
          orderId: 'TEST' + Date.now(),
          amount: 0.01,
          payType: 'alipay'
        });
        uni.hideLoading();
        this.showResult('支付成功', result);
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        });
      } catch (error) {
        uni.hideLoading();
        this.showError(error);
      }
    },
    
    // 选择图片
    async handleChooseImage() {
      if (!this.checkAppEnv()) return;
      
      try {
        const result = await callAppChooseImage({
          maxCount: 3,
          allowCamera: true
        });
        this.showResult('图片选择成功', result);
      } catch (error) {
        this.showError(error);
      }
    },
    
    // 获取定位
    async handleGetLocation() {
      if (!this.checkAppEnv()) return;
      
      try {
        uni.showLoading({ title: '定位中...' });
        const result = await getAppLocation();
        uni.hideLoading();
        this.showResult('定位成功', result);
      } catch (error) {
        uni.hideLoading();
        this.showError(error);
      }
    },
    
    // 设置标题
    async handleSetTitle() {
      if (!this.checkAppEnv()) return;
      
      try {
        await setAppTitle('新的标题 - ' + Date.now());
        uni.showToast({
          title: '标题已设置',
          icon: 'success'
        });
      } catch (error) {
        this.showError(error);
      }
    },
    
    // 关闭 WebView
    async handleClose() {
      if (!this.checkAppEnv()) return;
      
      uni.showModal({
        title: '提示',
        content: '确定要关闭 WebView 吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await closeAppWebView();
            } catch (error) {
              this.showError(error);
            }
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.app-bridge-test {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;
}

.header {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .status-box {
    display: flex;
    align-items: center;
    
    .status-label {
      font-size: 28rpx;
      color: #666;
      margin-right: 10rpx;
    }
    
    .status-value {
      font-size: 28rpx;
      font-weight: 500;
      
      &.success {
        color: #52c41a;
      }
      
      &.warning {
        color: #faad14;
      }
    }
  }
}

.content {
  .section {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    
    .section-title {
      display: block;
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }
  }
}

.btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
  border: none;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
  
  &.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
  }
  
  &.btn-info {
    background: linear-gradient(135deg, #00c6ff 0%, #0072ff 100%);
    color: #fff;
  }
  
  &.btn-success {
    background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
    color: #fff;
  }
  
  &.btn-warning {
    background: linear-gradient(135deg, #faad14 0%, #fa8c16 100%);
    color: #fff;
  }
  
  &.btn-secondary {
    background: linear-gradient(135deg, #8c8c8c 0%, #595959 100%);
    color: #fff;
  }
  
  &.btn-light {
    background: #f5f5f5;
    color: #333;
  }
  
  &.btn-danger {
    background: linear-gradient(135deg, #ff4d4f 0%, #cf1322 100%);
    color: #fff;
  }
}

.result-box {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .result-title {
    display: block;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .result-text {
    display: block;
    font-size: 24rpx;
    color: #666;
    line-height: 1.6;
    white-space: pre-wrap;
    word-break: break-all;
    background: #f5f5f5;
    padding: 20rpx;
    border-radius: 10rpx;
  }
}
</style>
